//
//  homeViewController.m
//  erhuo
//
//  Created by Jingru Nie on 14/12/28.
//  Copyright (c) 2014年 集易（北京）科技有限公司. All rights reserved.
//

#import "homeViewController.h"
#import "settingViewController.h"
#import "UICircleTextField.h"
#import "NSNetwork.h"
//#import "UIFocusView.h"
#import "PostMessa-Prefix.pch"
//#import "sellViewController.h"
//#import "sellDetailViewController.h"
//#import "searchViewController.h"
//#import "MobClick.h"
//#import "settingViewController.h"
//#import "webViewController.h"
//#import "UIImagePlayer.h"
//#import "NSToast.h"
#import <AssetsLibrary/ALAsset.h>
//ALAsset类代表相册中的每个资源文件
//ALAssetRepresentation类代表相册中每个资源文件的详细信息，可以通过它获取资源的大小，名字，路径等详细信息
@interface homeViewController () <UITextFieldDelegate>
{
    NSArray *classImages;
    NSArray *classImagesClicked;
    UICircleTextField *searchBar;
//    UIImagePlayer *player;
//    UIFocusView *focusV;
    UIScrollView *classV;
}

@end

#define TITLEHEIGHT (self.view.bounds.size.height < 568.0f ? 16 : 18) //导航栏字体大小
#define NAVMARGINLEFT 15   //左边空隙
#define NAVMARGINTOP (self.view.bounds.size.height < 568.0f ? 5 : 8)   //顶部空隙
#define FOCUSHEIGHT  (self.view.bounds.size.height < 568.0f ? 180 : 220)  //焦点图高度
#define CLASSHEIGHT (self.view.bounds.size.height - (NAVHEIGHT + FOCUSHEIGHT + BOTTOMBARHEIGHT)) //分类列表高度

@implementation homeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNeedsStatusBarAppearanceUpdate];
    
    classImages = [NSArray array];
    classImagesClicked = [NSArray array];

    [self navInit];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)navInit {
    //顶部导航栏
    UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 75)];
    [navBar setBackgroundColor:ERHUORED(1.0f)];
    [self.view addSubview:navBar];
    
    //导航栏左侧文字
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, STATUSHEIGHT, navBar.frame.size.width / 6, NAVBARHEIGHT)];
    btn.titleLabel.textColor = [UIColor blackColor];
//    imgV.contentEdgeInsets = []
    btn.contentVerticalAlignment =  UIControlContentVerticalAlignmentCenter;
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [btn setTitleColor:ERHUOTEXT forState:UIControlStateNormal];
//    [imgV.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btn setTitle:@"TITLE" forState:UIControlStateNormal];
    
    UITapGestureRecognizer *gis = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setting)];
//    NSURL *url = [NSURL URLWithString:@"http://img3.douban.com/icon/g12570-3.jpg"];
//    UIImage *tmpImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
//    [imgV setImage:tmpImg forState:UIControlStateNormal];
    gis.numberOfTapsRequired = 1;
    gis.numberOfTouchesRequired = 1;
    [btn addGestureRecognizer:gis];
    [navBar addSubview:btn];
    
    //
    UITextField *searchField = [[UITextField alloc] initWithFrame:CGRectMake(navBar.frame.size.width/6,STATUSHEIGHT ,navBar.frame.size.width * 3 / 6 , NAVBARHEIGHT)];
    [searchField setBackgroundColor:[UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:0.2]];
    
    searchField.placeholder = @"输入内容";
    [navBar addSubview:searchField];
    [self.view setBackgroundColor: [UIColor whiteColor]];
}

- (void)setting {
    NSLog(@"click once settting!");
//    [searchBar resignFirstResponder];
//
    settingViewController *setVC = [[settingViewController alloc] initWithViewController:self];
    CATransition* transition = [CATransition animation];
    //过渡类型
    transition.type = kCATransitionPush;
    //过渡方向
    transition.subtype = kCATransitionFromLeft;
    //
    [self.tabBarController.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    [self.tabBarController.navigationController pushViewController:setVC animated:NO];
//    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
//
//    [self.navigationController pushViewController:setVC animated:NO];
}

- (void)search {
//    [searchBar resignFirstResponder];
//    searchViewController *searchVC = [[searchViewController alloc] init];
//    [self.tabBarController.navigationController pushViewController:searchVC animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [searchBar resignFirstResponder];
}

#define BANNERHEIGHT 25
#define BANNERLEFT 15

- (void)focusData {
//    NSMutableDictionary *data = [NSMutableDictionary dictionary];
//    [data setValue:@"1" forKey:@"client"];
//    
//    [self.view addSubview:player];
//    [player startPlaying];
//    
//    NSNetwork *net = [[NSNetwork alloc] initWithURL:[NSURL URLWithString:[HTTPREQUESTBASE stringByAppendingString:@"recommend_goods_list/"]] withMethod:_NETWORK_METHOD_POST_ withData:data withType:_NETWORK_DATA_TYPE_TEXT_];
//    [net setTimeoutInterval:10];
//    
//    [net sendRequest:^(NSURLResponse *response, NSData *data, NSError *error){
//        if (!error) {
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            NSArray *focusData = [dic objectForKey:@"data"];
//            [[NSUserDefaults standardUserDefaults] setObject:focusData forKey:@"focusData"];
//            [self focusInit:focusData];
//        }else {
//            [NSToast showToast:@"网络似乎有问题" inView:self.view];
//            [player stopPlaying];
//            [player removeFromSuperview];
//        }
//    }];
}
//
- (void)focusInit:(NSArray *)focusData {
//    if (focusV) {
//        [focusV removeFromSuperview];
//    }
//    focusV = [[UIFocusView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT, self.view.frame.size.width,  FOCUSHEIGHT)];
//    
//    NSMutableArray *imageViews = [NSMutableArray array];
//    
//    for (NSDictionary *dic in focusData) {
//        
//        NSString *img = [dic valueForKey:@"recommend_img"];
//        
//        UIImageView *webV = [[UIImageView alloc] initWithFrame:focusV.bounds];
//        if ([img length] > 0) {
//            [webV setImageURL:[NSURL URLWithString:img]];
//        }
//        webV.contentMode = UIViewContentModeScaleAspectFill;
//        webV.clipsToBounds = YES;
//        
//        /*if ([[dic valueForKey:@"target"] integerValue] != 1) {
//            UIView *bannerV = [[UIView alloc] initWithFrame:CGRectMake(BANNERLEFT, 0, focusV.bounds.size.width - BANNERLEFT * 2, BANNERHEIGHT)];
//            
//            //价格标签
//            UILabel *priceL = [[UILabel alloc] initWithFrame:bannerV.bounds];
//            priceL.text = [@"￥" stringByAppendingString:[dic valueForKey:@"price"]];
//            priceL.font = [UIFont systemFontOfSize:15];
//            priceL.textColor = [UIColor whiteColor];
//            priceL.textAlignment = NSTextAlignmentLeft;
//            [priceL sizeToFit];
//            priceL.frame = CGRectMake(0, 0, priceL.frame.size.width, BANNERHEIGHT);
//            [bannerV addSubview:priceL];
//            
//            //商品标题标签
//            UILabel *titleL = [[UILabel alloc] initWithFrame:bannerV.bounds];
//            titleL.text = [dic valueForKey:@"title"];
//            titleL.font = [UIFont systemFontOfSize:15];
//            titleL.textColor = [UIColor whiteColor];
//            titleL.textAlignment = NSTextAlignmentLeft;
//            [titleL sizeToFit];
//            
//            float x = bannerV.bounds.size.width - titleL.frame.size.width;
//            if (x < priceL.frame.size.width + BANNERLEFT) {
//                x = priceL.frame.size.width + BANNERLEFT;
//            }
//            titleL.frame = CGRectMake(x, 0, bannerV.frame.size.width - x, BANNERHEIGHT);
//            [bannerV addSubview:titleL];
//            
//            UIView *banner = [[UIView alloc] initWithFrame:CGRectMake(0, webV.frame.size.height - BANNERHEIGHT, webV.frame.size.width, bannerV.frame.size.height)];
//            [banner setBackgroundColor:ERHUORED(0.8f)];
//            [banner addSubview:bannerV];
//            [webV addSubview:banner];
//        }*/
//        
//        [imageViews addObject:webV];
//    }
//    UINavigationController *innerNav = self.navigationController;
//    UINavigationController *outterNav = self.tabBarController.navigationController;
//    
//    if (imageViews.count > 0) {
//        [focusV setImageViewSet:imageViews scrollType:FOCUSSCROLLTYPEHORIZONAL tapBlock:^(NSInteger index) {
//            NSDictionary *dic = [focusData objectAtIndex:index];
//            switch ([[dic objectForKey:@"target"] integerValue]) {
//                case 0: {
//                    sellDetailViewController *detailVC = [[sellDetailViewController alloc] initWithSID:[dic objectForKey:@"id"] data:nil fromUserPage:NO];
//                    [outterNav pushViewController:detailVC animated:YES];
//                }
//                    break;
//                case 1: {
//                    //网络链接
//                    webViewController *webVC = [[webViewController alloc] initWithURL:[NSURL URLWithString:[dic objectForKey:@"url"]] title:[dic objectForKey:@"title"]];
//                    [outterNav pushViewController:webVC animated:YES];
//                }
//                    break;
//                case 2: {
//                    NSString *cid = [dic objectForKey:@"target_cid"];
//                    NSString *cname = [dic objectForKey:@"target_cname"];
//                    
//                    [[NSNotificationCenter defaultCenter] postNotificationName:@"classSelect" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:cid, @"index", nil]];
//                    sellViewController *sellVC = [[sellViewController alloc] initWithID:cid withName:cname];
//                    
//                    [innerNav pushViewController:sellVC animated:YES];
//                }
//                    break;
//                    
//                default:
//                    break;
//            }
//        }];
//        //[focusV setDotsRect:CGRectMake(0, focusV.frame.size.height - BANNERHEIGHT * 2, focusV.frame.size.width, BANNERHEIGHT)];
//        [focusV setDotsColor:ERHUORED(0.5f) highlightColor:ERHUORED(1.0f)];
//        [focusV setTimeInterval:5];
//    }
//    
//    [self.view addSubview:focusV];
//    
//    UIView *split = [[UIView alloc] initWithFrame:CGRectMake(0, focusV.frame.size.height - BORDERWIDTH * 8, focusV.frame.size.width, BORDERWIDTH * 8)];
//    [split setBackgroundColor:ERHUORED(1.0f)];
//    [focusV addSubview:split];
}

#define CLASSMARGINLEFT 9
#define CLASSLISTMARGINLEFT 15
#define CLASSBTNHEIGHT (self.view.bounds.size.height < 568.0f ? 76 : 86)
#define CLASSBTNWIDTH 66
#define IMAGEVIEWHEIGHT (CLASSBTNHEIGHT - 25)
#define CLASSMARGINTOP ((CLASSHEIGHT - CLASSBTNHEIGHT * 2) / 3)

- (void)classData {
//    NSMutableDictionary *data = [NSMutableDictionary dictionary];
//    [data setValue:@"1" forKey:@"client"];
//    
//    NSNetwork *net = [[NSNetwork alloc] initWithURL:[NSURL URLWithString:[HTTPREQUESTBASE stringByAppendingString:@"goods_class_list/"]] withMethod:_NETWORK_METHOD_POST_ withData:data withType:_NETWORK_DATA_TYPE_TEXT_];
//    [net setTimeoutInterval:10];
//    
//    [net sendRequest:^(NSURLResponse *response, NSData *data, NSError *error){
//        if (!error) {
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            NSArray *classData = [dic objectForKey:@"data"];
//            
//            //告知 mainVC 数据已经拿到
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"slideUpdate" object:nil];
//            [[NSUserDefaults standardUserDefaults] setObject:classData forKey:@"classData"];
//            [self classInit:classData];
//        }
//    }];
}

- (void)classInit:(NSArray *)classData {
//    //分类页面
//    if (classV) {
//        [classV removeFromSuperview];
//    }
//    classV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT + FOCUSHEIGHT, self.view.bounds.size.width, CLASSHEIGHT)];
//    classV.showsHorizontalScrollIndicator = NO;
//    classV.showsVerticalScrollIndicator = NO;
//    classV.bounces = NO;
//    
//    int index = 0;
//    for (NSDictionary *dic in classData) {
//        UIButton *classBtn = [[UIButton alloc] initWithFrame:CGRectMake(CLASSLISTMARGINLEFT + index % 4 * (CLASSMARGINLEFT + CLASSBTNWIDTH), CLASSMARGINTOP + index / 4 * (CLASSMARGINTOP + CLASSBTNHEIGHT), CLASSBTNWIDTH, CLASSBTNHEIGHT)];
//        [classBtn setBackgroundColor:[UIColor whiteColor]];
//        [classBtn.layer setCornerRadius:10];
//        [classBtn.layer setBorderColor:[ERHUORED(0.4f) CGColor]];
//        [classBtn.layer setBorderWidth:BORDERWIDTH];
//        
//        NSString *img = [dic valueForKey:@"icon"];
//        
//        UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(CLASSLISTMARGINLEFT, 0, classBtn.bounds.size.width - CLASSLISTMARGINLEFT * 2, IMAGEVIEWHEIGHT)];
//        //imgV.frame = CGRectInset(imgV.bounds, (imgV.bounds.size.width - [[dic objectForKey:@"new_icon_width"] floatValue] / [[UIScreen mainScreen] scale]) / 2, (imgV.bounds.size.height - [[dic objectForKey:@"new_icon_height"] floatValue] / [[UIScreen mainScreen] scale]) / 2);
//        if ([img length] > 0) {
//            [imgV setImageURL:[NSURL URLWithString:img]];
//        }
//        imgV.contentMode = UIViewContentModeScaleAspectFit;
//        [classBtn addSubview:imgV];
//        
//        [classBtn setTitleEdgeInsets:UIEdgeInsetsMake(IMAGEVIEWHEIGHT, 0, 0, 0)];
//        
//        [classBtn setTitle: [dic objectForKey:@"cname"] forState: UIControlStateNormal];
//        [classBtn setTitle: [dic objectForKey:@"cname"] forState: UIControlStateHighlighted];
//        [classBtn setTitleColor:ERHUOTEXT forState:UIControlStateNormal];
//        [classBtn setTitleColor:ERHUOTEXT forState:UIControlStateHighlighted];
//        classBtn.titleLabel.font = [UIFont systemFontOfSize:11];
//        classBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
//        classBtn.contentMode = UIControlContentVerticalAlignmentTop;
//        classBtn.tag = IMAGETAG + index;
//        [classBtn addTarget:self action:@selector(classTapped:) forControlEvents:UIControlEventTouchUpInside];
//        [classV addSubview:classBtn];
//        
//        index++;
//    }
//    [self.view addSubview:classV];
//    [player stopPlaying];
//    [player removeFromSuperview];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self search];
    return YES;
}


- (void)classTapped:(UIButton *)sender {
//    NSString *cid = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"classData"] objectAtIndex:(sender.tag - IMAGETAG)] objectForKey:@"cid"];
//    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"classSelect" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", (long)sender.tag - IMAGETAG], @"index", nil]];
//    sellViewController *sellVC = [[sellViewController alloc] initWithID:cid withName:sender.titleLabel.text];
//    
//    [self.navigationController pushViewController:sellVC animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [MobClick beginLogPageView:@"homePage"];
    
    //焦点图数据
    NSArray *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"focusData"];
    if (data.count > 0) {
        [self focusInit:data];
    }else {
        [self focusData];
    }
    //分类图数据
    data = [[NSUserDefaults standardUserDefaults] objectForKey:@"classData"];
    if (data.count > 0) {
        [self classInit:data];
    }else {
        [self classData];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [MobClick endLogPageView:@"homePage"];
}

@end
